//
//  UICollectionViewLeftAlignedLayout.swift
//  fho
//
//  Created by 郭颢源 on 2021/3/24.
//

import UIKit


extension UICollectionViewLayoutAttributes{

    func leftAlignFrameWithSectionInset(inset:UIEdgeInsets) {
        var frame:CGRect = self.frame
        frame.origin.x = inset.left
        self.frame = frame
    }
}
protocol UICollectionViewDelegateLeftAlignedLayout:UICollectionViewDelegateFlowLayout {

}
class UICollectionViewLeftAlignedLayout: UICollectionViewFlowLayout {
    //所有cell的布局属性
    var layoutAttributes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    override init() {
        super.init();
        self.itemSize = CGSize(width: 70, height: 40)  //这里可以根据自己的需求设置大小
        self.scrollDirection = .horizontal
//        self.numRow = 7;
//        self.numCol = 4;
//        self.contentInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    //计算布局
//    override func prepare() {
//
//    let numsection = self.collectionView!.numberOfSections;
//    let itemNum: Int = self.collectionView!.numberOfItems(inSection: 0)
//        layoutAttributes.removeAll();
//        for i in 0..<numsection{
//            for j in 0..<itemNum{
//                let layout = self.layoutAttributesForItem(at: IndexPath(item: j, section: i))!;
//                self.layoutAttributes.append(layout);
//            }
//        }
//
//    }
    
    /**
       用来计算出rect这个范围内所有cell的UICollectionViewLayoutAttributes，
       并返回。
       */
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//        let originalAttributes:Array = super.layoutAttributesForElements(in: rect)!
//        var updatedAttributes:Array = super.layoutAttributesForElements(in: rect)!
//        for attributes in originalAttributes {
//            if (attributes.representedElementKind != nil) {
//                let index = updatedAttributes.firstIndex(of: attributes)
//                updatedAttributes[index!] = self.layoutAttributesForItem(at: attributes.indexPath)!
//            }
//
//        }
//        return updatedAttributes
        
        super.layoutAttributesForElements(in: rect)
        
        //使用系统帮我们计算好的结果
        guard let attributes = super.layoutAttributesForElements(in: rect) else {
            return nil
        }
        
        //第0个cell没有上一个cell，所以从1开始
        for i in 1..<attributes.count {
            let curAttr = attributes[i]
            let preAttr = attributes[i-1]
            
//            let origin = preAttr.frame.maxX
//            //根据maximumInteritemSpacing计算出的新的x位置
//            let targetX = origin + self.minimumInteritemSpacing
//            //只有系统计算的间距大于maximumInteritemSpacing时才进行调整
//            if curAttr.frame.minX > targetX {
//                // 换行时不用调整
//                if targetX + curAttr.frame.width < collectionViewContentSize.width {
//                    var frame = curAttr.frame
//                    frame.origin.x = targetX
//                    curAttr.frame = frame
//                }
//            }
            
            let origin = preAttr.frame.maxX+self.minimumInteritemSpacing+curAttr.frame.width
            if origin > (self.collectionView?.bounds.width)! {
                curAttr.frame.origin.x = 0
                curAttr.frame.origin.y = preAttr.frame.maxY + self.minimumLineSpacing
            }else
            {
                curAttr.frame.origin.x = preAttr.frame.maxX + self.minimumInteritemSpacing
                curAttr.frame.origin.y = preAttr.frame.minY 
            }
            
            
        }
        return attributes
    }


    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let layoutAttribute = super.layoutAttributesForItem(at: indexPath)
        
        let sectionInset = evaluatedSectionInsetForItemAtIndex(index: indexPath.section)
        let isFirstItemInSection:Bool = indexPath.item == 0
        let layoutWidth:CGFloat = (self.collectionView?.frame.width)! - sectionInset.left - sectionInset.right;
        if isFirstItemInSection {
            layoutAttribute?.leftAlignFrameWithSectionInset(inset: sectionInset)
            return layoutAttribute
        }
        
        let previousIndexPath:IndexPath = IndexPath(item: indexPath.item-1, section: indexPath.section)
        
        let previousFrame:CGRect = self.layoutAttributesForItem(at: previousIndexPath)!.frame
        let previousFrameRightPoint:CGFloat = previousFrame.origin.x + previousFrame.size.width
        let currentFrame:CGRect = layoutAttribute!.frame
        let strecthedCurrentFrame:CGRect = CGRect(x: sectionInset.left,
                                                  y: currentFrame.origin.y,
                                                  width: layoutWidth,
                                                  height: currentFrame.size.height)
        // if the current frame, once left aligned to the left and stretched to the full collection view
        // widht intersects the previous frame then they are on the same line
        let isFirstItemInRow:Bool = !previousFrame.intersects(strecthedCurrentFrame)

        if isFirstItemInRow {
            // make sure the first item on a line is left aligned
            layoutAttribute?.leftAlignFrameWithSectionInset(inset: sectionInset)
            return layoutAttribute
        }

        var frame:CGRect = layoutAttribute!.frame
        frame.origin.x = previousFrameRightPoint + evaluatedMinimumInteritemSpacingForSectionAtIndex(sectionIndex: indexPath.section)
//            [self evaluatedMinimumInteritemSpacingForSectionAtIndex:indexPath.section];
        layoutAttribute?.frame = frame
        return layoutAttribute
    }
//    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//
//        return self.layoutAttributes
//    }
    
    func evaluatedMinimumInteritemSpacingForSectionAtIndex(sectionIndex:NSInteger) -> CGFloat {
        weak var delegate = self.collectionView!.delegate as? UICollectionViewDelegateLeftAlignedLayout
        if delegate != nil {
            return (delegate?.collectionView?(collectionView!, layout: self, minimumLineSpacingForSectionAt: sectionIndex))!
        }else
        {
            return self.minimumInteritemSpacing
        }

        
    }
    func evaluatedSectionInsetForItemAtIndex(index:NSInteger) -> UIEdgeInsets {
        weak var delegate = self.collectionView!.delegate as? UICollectionViewDelegateLeftAlignedLayout
        if delegate != nil {
            return (delegate?.collectionView?(self.collectionView!, layout: self, insetForSectionAt: index))!
        } else {
            return self.sectionInset
        }
        
    }
}


